<template>
  <el-card style="max-width: 100%">
    <ElButton
      type="primary"
      icon="plus"
      size="small"
      style="margin: 10px 0"
      @click="addTrademark"
    >
      添加品牌
    </ElButton>
    <el-table border style="width: 100%" :data="trademarkList">
      <el-table-column label="序号" width="80" align="center" type="index" />
      <el-table-column label="品牌名称">
        <template #="{ row }">
          <h1>{{ row.tmName }}</h1>
        </template>
      </el-table-column>
      <el-table-column label="品牌logo">
        <template #="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 40px; height: 40px" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #="{ row }">
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateTrademark(row)"
          ></el-button>
          <el-popconfirm
            :title="`你确定要删除${row.tmName}?`"
            icon="Delete"
            width="200px"
            icon-color="red"
            @confirm="handleDelte(row)"
          >
            <template #reference>
              <el-button type="danger" size="small" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="limitShowNum"
      :page-sizes="[3, 5, 7, 9]"
      :background="true"
      layout="prev, pager, next, jumper,->, sizes, total"
      :total="total"
      size="small"
      @change="valTrademarkList"
    />
  </el-card>
  <!-- 对话框组件 -->
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500">
    <el-form
      label-width="100px"
      :rules="rules"
      :model="trademarkInfo"
      ref="formRef"
    >
      <el-form-item label="品牌名称" prop="tmName">
        <el-input v-model="trademarkInfo.tmName"></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          :action="`${BASEAPI}/admin/product/fileUpload`"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :headers="headers"
        >
          <img
            v-if="trademarkInfo.logoUrl"
            :src="trademarkInfo.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="default" @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import {
  ElButton,
  ElCard,
  ElTable,
  ElPagination,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElPopconfirm,
} from 'element-plus'
import type { FormRules } from 'element-plus'
import { ref, onMounted, reactive, nextTick } from 'vue'
import type { UploadProps } from 'element-plus'
import type {
  Record,
  TrademarkListResponseType,
} from '@/api/product/trademark/types'
import { useUserStore } from '@/store/modules/user'
import {
  reqTrademarkList,
  reqAddTrademark,
  reqUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark'
import type { Rollup } from 'vite'
//用户仓库
const userStore = useUserStore()
const headers = { Token: userStore.token }
const formRef = ref()
//对话框标题
let dialogTitle = ref<string>('')
//当前页
let pageNum = ref<number>(1)
//每页显示个数
let limitShowNum = ref<number>(3)
//总页数
let total = ref<number>(0)
//存储返回的数据列表
let trademarkList = ref<Record[]>([])
//控制对话框显示或隐藏
let dialogFormVisible = ref<boolean>(false)
//收集品牌信息用于更新或者添加品牌
const trademarkInfo = reactive<Record>({ tmName: '', logoUrl: '' })
//获取环境变量
const BASEAPI = import.meta.env.VITE_APP_BASE_API

//校验tmName函数
const checkTmName = (rule: any, value: any, callback: any) => {
  console.log(value)
  if (value.length < 2) {
    callback(new Error('品牌名字大于2位'))
  } else {
    callback()
  }
}
//校验logoUrl函数
const checkLogoUrl = (rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('请上传图片'))
  }
}
const rules = reactive<FormRules<typeof trademarkInfo>>({
  tmName: [{ required: true, trigger: 'blur', validator: checkTmName }],
  logoUrl: [{ required: true, validator: checkLogoUrl }],
})
//处理删除品牌
const handleDelte = async (row: Record) => {
  try {
    await reqDeleteTrademark(row.id as number)
    ElMessage.success('删除成功')
    valTrademarkList()
  } catch {
    ElMessage.error('删除失败')
  }
}

//上传图片前的处理函数钩子
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('图片必须是JPG或者PNG格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB')
    return false
  }
  return true
}
//上传图片成功时的函数钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  trademarkInfo.logoUrl = response.data
  formRef.value.clearValidate('logoUrl')
}
//存储获得的商标数据
const valTrademarkList = async () => {
  const res: TrademarkListResponseType = await reqTrademarkList(
    pageNum.value,
    limitShowNum.value,
  )
  if (res.code === 200) {
    total.value = res.data.total
    trademarkList.value = res.data.records
  }
}
//添加品牌
const addTrademark = () => {
  dialogTitle.value = '添加品牌'
  dialogFormVisible.value = true
  nextTick(() => {
    formRef.value.resetFields()
  })
}
//展示品牌信息
const showTrademarkInfo = (id: number): void => {
  const obj: Record = trademarkList.value.find((ele) => ele.id === id) as Record
  trademarkInfo.tmName = obj.tmName
  trademarkInfo.logoUrl = obj.logoUrl
  trademarkInfo.id = id
}
//跟新品牌信息
const updateTrademark = (row: Record) => {
  dialogTitle.value = '修改品牌'
  dialogFormVisible.value = true
  nextTick(() => {
    formRef.value.resetFields()
    showTrademarkInfo(row.id as number)
  })
}

const cancel = (): void => {
  dialogFormVisible.value = false
}

const confirm = async () => {
  //在确认前对表单进行校验
  await formRef.value.validate()
  dialogFormVisible.value = false
  if (dialogTitle.value === '添加品牌') {
    try {
      await reqAddTrademark(trademarkInfo)
      ElMessage.success('添加品牌成功')
      valTrademarkList()
    } catch (error) {
      ElMessage.error((error as Error).message)
    }
  } else {
    try {
      await reqUpdateTrademark(trademarkInfo)
      ElMessage.success('修改品牌成功')
      valTrademarkList()
    } catch (error) {
      ElMessage.error((error as Error).message)
    }
  }
}

onMounted(() => {
  valTrademarkList()
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
